package com.feihong.txgw.ui.fragment.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.TypedValue;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.ui.activity.HomeActivity;
import com.feihong.txgw.ui.activity.product.ProductInfoActivity;
import com.feihong.txgw.ui.activity.setting.ServiceMessageActivity;
import com.feihong.txgw.ui.activity.user.LiuLiangChaXunActivity;
import com.feihong.txgw.ui.fragment.base.BaseFragment;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.view.WebView4Scroll;
import com.just.agentweb.AgentWeb;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;

import static android.view.View.OVER_SCROLL_NEVER;


/**
 * Created by Sabirjan on 2017/6/13.
 * TXGW.
 * 飞宏电子
 * 发现Fragment Tab2
 */
public class DiscoverFragment extends BaseFragment {

    @BindView(R.id.webviewframe)
    RelativeLayout webviewFrame;
    private AgentWeb mAgentWeb;
    @BindView(R.id.swiperefreshlayout)
    SwipeRefreshLayout mswiperefreshlayout;
    @BindView(R.id.img_btn_message)
    ImageButton mMesBtn;
    @BindView(R.id.txt_title)
    TextView mDisconverTitle;
    private AgentWeb.PreAgentWeb mPreAgentWeb;
    public static final String INTENT_PRODUCTID = "INTENT_PRODUCTID";
    public static final String INTENT_NAME = "productname";

    public static DiscoverFragment newInstance(String tabName) {
        DiscoverFragment discoverFragment = new DiscoverFragment();
        discoverFragment.tag = tabName;
        return discoverFragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mDisconverTitle.setText("发现");
    }

    @Override
    public void setTheme() {
    }

    @Override
    public int setLayoutID() {
        return R.layout.fragment_discover;
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);

        EventBus.getDefault().register(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                //绑定View
                initView();
//
//        //绑定数据
                bindData();
            }
        }, 200);
    }


    @Override
    public void initView() {

        // AgentWeb 保持了 WebView 的使用 ，
        //设置刷新时动画的颜色，可以设置4个
        mswiperefreshlayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        mswiperefreshlayout.setColorSchemeResources(R.color.appRed,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        mswiperefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        mswiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadPage();
            }
        });
        //同步 Cookie
        //AgentWebConfig.syncCookies("http://www.djml.com","ID=XXXX")
    }

    @Override
    public void onDestroy() {
        try {
            if (mAgentWeb != null) {
                mAgentWeb.destroy();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        super.onDestroy();
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return true;
            // return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

            return true;
//             return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mswiperefreshlayout.setRefreshing(false);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };
    //WebChromeClient
    private WebChromeClient mWebChromeClient = new WebChromeClient() {

    };

    @Override
    public void bindData() {
        WebView4Scroll webView4Scroll = new WebView4Scroll(getActivity(), mswiperefreshlayout);
        webView4Scroll.setVerticalScrollBarEnabled(false);
        webView4Scroll.setOverScrollMode(OVER_SCROLL_NEVER);
        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(webviewFrame, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient).setWebView(webView4Scroll)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_errorlayout, R.id.agentweb_re_query_data_layout)
                .createAgentWeb()
                .ready();

        loadPage();
    }

    private void loadPage() {
        String requesturl = HttpTools.DISCOVER_HOME + System.currentTimeMillis();

        mAgentWeb = mPreAgentWeb.go(requesturl);
        mAgentWeb.getAgentWebSettings().getWebSettings().setGeolocationEnabled(false);

        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new DiscoverInterface(mAgentWeb, _mActivity, new ActionCallBack() {
            @Override
            public void serviceHelper() {
                //客户服务
                Intent intentHelper = new Intent(_mActivity, ServiceMessageActivity.class);
                startActivity(intentHelper);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            }

            @Override
            public void selectResidue() {
                //余量查询
                if (!isUserLogin()) {
                    showLoginDialog();
                    return;
                }
                Intent intentResidue = new Intent(_mActivity, LiuLiangChaXunActivity.class);
                startActivity(intentResidue);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            }

            @Override
            public void goto_Detail(String detail) {
                LogUtils.i(TAG + ":分期购:" + detail);
                //分期购
                if (detail != null) {
                    JSONObject obj = JSON.parseObject(detail);

                    String sku_id = obj.getString("sku_id");
                    String sku_name = obj.getString("sku_name");
                    String goto_url = obj.getString("goto_url");

                    Intent intent = new Intent();
                    intent.setClass(getActivity(), ProductInfoActivity.class);
                    intent.putExtra(INTENT_PRODUCTID, sku_id);
                    intent.putExtra(ProductInfoActivity.INTENT_NAME, sku_name);
                    getActivity().startActivity(intent);
                }
            }
        }));

        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
    }
    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
//        mImmersionBar.statusBarDarkFont(true).statusBarColor(R.color.white).init();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mAgentWeb != null) {
            mAgentWeb.destroy();
        }
    }

    public interface ActionCallBack {
        void serviceHelper();

        void selectResidue();

        void goto_Detail(String detail);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            if (((HomeActivity) _mActivity).isHaveNewMsg) {
                mMesBtn.setImageResource(R.mipmap.unread_msg);
            } else {
                mMesBtn.setImageResource(R.mipmap.message_normal_icon);
            }
        }
    }
}



